import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xim/screen/message_list_screen/page/chat_room_info_page.dart';
import 'package:xim/widget/Icon/my_icon.dart';
import 'package:xim/widget/dash_chat_2/dash_chat_2.dart';
import 'package:xim/screen/message_list_screen/widget/chat_avatar.dart';
import 'package:xim/screen/message_list_screen/widget/chat_bottom_action_panel.dart';
import 'package:xim/screen/message_list_screen/widget/chat_bottom_face_panel.dart';
import 'package:xim/screen/message_list_screen/widget/date_separator.dart';
import 'package:xim/screen/message_list_screen/widget/message_row_widget.dart';
import 'package:xim/screen/page/photo_view_page.dart';
import 'package:xim/common/util/getx.dart';

import 'chat_detail_page_controller.dart';

class ChatDetailPage extends StatefulWidget {
  const ChatDetailPage({Key? key}) : super(key: key);

  @override
  State<ChatDetailPage> createState() => _ChatDetailPageState();
}

class _ChatDetailPageState extends State<ChatDetailPage> {
  /// 聊天框背景颜色
  final Color? chatWindowsBgColor = const Color(0xffededed);
  /// 聊天输入框 placeholder 提示文本
  final String inputHintText = "";
  /// 聊天输入框 水平 margin
  final double inputHorizontalMargin = 4;
  /// 聊天输入框背景颜色
  final Color textFieldBgColor = const Color(0xffffffff);
  /// 底部面板背景颜色
  late Color? bottomBarBgColor = chatWindowsBgColor;
  /// appBar 背景颜色
  late final Color? appBarBgColor =  chatWindowsBgColor;
  /// appBar 字体颜色
  final Color appBarFontColor = Colors.black;
  /// 输入框与聊天框间的分割线 border
  final BorderSide bottomBarDivider = const BorderSide(width: 1.2, color: Color(0xd2d2d2d2));
  /// 消息输入框最大行数
  final int inputMaxLines = 2;
  /// 正在展示的底部面板
  BottomPanel? _currBottomPanel;
  /// 底部输入框 focusNode
  final FocusNode _focusNode = FocusNode();
  /// 关闭底部弹出面板
  void closeBottomPanel() => setState(() { _currBottomPanel = null;});

  var controller = ChatDetailPageController();

  /// 打开指定的底部弹出面板
  void openBottomPanel(BottomPanel panel) {
    if (inputOptions.focusNode!=null && inputOptions.focusNode!.hasFocus) {
      FocusScope.of(context).requestFocus(FocusNode());
    }
    setState(() {
      _currBottomPanel = panel;
    });
  }

  /// 底部面板
  List<BottomPanel> bottomPanel = [
    BottomPanel(0, ChatBottomFacePanel(height: 500, ), 300, const Icon(Icons.mood)),
    BottomPanel(1, ChatBottomActionPanel(height: 200,), 200, const Icon(Icons.add_circle_outline),),
  ];

  @override
  void initState() {
    super.initState();
    _focusNode.addListener(() {
      if (_focusNode.hasFocus) {
        closeBottomPanel();
      }
    });
  }
  PreferredSizeWidget? get appBar => AppBar(
    actionsIconTheme: IconThemeData(
      color: appBarFontColor,
    ),
    elevation: 0.15,
    iconTheme: IconThemeData(
      color: appBarFontColor,
    ),
    // leading: Icon(Icons.arrow_back_ios_outlined),
    title: Text("Flutter 交流群(22/35)", style: TextStyle(color: appBarFontColor, fontSize: 16),),
    centerTitle: true,
    backgroundColor: appBarBgColor,
    actions: [
      IconButton(onPressed: () {
        Get.to(ChatRoomInfoPage());
      }, icon: const Icon(Icons.more_horiz,))
    ],
  );
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: Column(
        children: [
          // 消息窗口
          Expanded(
              child: DashChat(
                onDashClick: () {
                  closeBottomPanel();
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                inputOptions: inputOptions,
                scrollToBottomOptions: const ScrollToBottomOptions( disabled: true),
                messageOptions: messageOptions,
                messageListOptions: messageListOptions,
                currentUser: controller.state.currUser,
                onSend: (ChatMessage m) => controller.sendMessage(m),
                messages: controller.state.messages,
              )
          ),
          // 底部面板
          AnimatedContainer(
            color: const Color.fromARGB(0, 237, 237, 237),
            duration: const Duration( milliseconds: 300, ),
            height: _currBottomPanel?.height ?? 0,
            child: _currBottomPanel?.panel,
          ),
        ],
      ),
    );
  }

  InputOptions get inputOptions => InputOptions(
      inputToolbarStyle: BoxDecoration(
        color: bottomBarBgColor,
        border: Border( top: bottomBarDivider, )
      ),
      // 自定义发送Icon
      sendButtonBuilder: (send){
        return InkWell(
          onTap: send,
          child: Container(
            margin: const EdgeInsets.only(left: 3),
            padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 12),
            decoration: const BoxDecoration(
              color: Colors.blueAccent,
              borderRadius: BorderRadius.all(Radius.circular(8))
            ),
            child: const Text("发送", style: TextStyle(color: Colors.white,fontWeight: FontWeight.w400),),
          ),
        );
      },
      inputToolbarMargin: EdgeInsets.zero,
      inputDecoration: bottomInputDecoration,
      showTraillingBeforeSend: true,
      focusNode: _focusNode,
      inputHorizontalMargin: 4,
      inputMaxLines: inputMaxLines,
      trailing: trailing,
      textController: TextEditingController(),
      leading: [const Icon(MyIcon.voice3)],
      onTextChange:(String value){
        bool hasMessage = value.trim()!="";
        // 文本输入
        setState(() {
          bottomPanel[bottomPanel.length-1].condition= !hasMessage;
        });
      }
  );

  /// 用户输入框里面的内容
  String? get inputTextMessage => inputOptions.textController?.text;

  MessageListOptions get messageListOptions => MessageListOptions(
    showDateSeparator: true,
    dateSeparatorBuilder: (DateTime date) => DateSeparator(date: date),
    scrollPhysics: const BouncingScrollPhysics(),
    separatorFrequency: SeparatorFrequency.hours,
    scrollController: scrollController,
    bgColor: chatWindowsBgColor
  );

  /// 自定义 聊天对话框底部输入框样式
  InputDecoration get bottomInputDecoration => InputDecoration(
        isDense: true,
        hintText: inputHintText,
        filled: true,
        fillColor: textFieldBgColor,
        contentPadding: const EdgeInsets.only(left: 18, top: 10, bottom: 10,),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(8),
          borderSide: const BorderSide( width: 0,style: BorderStyle.none, ),
        ),
      );

  /// 自定义消息展示样式
  BoxDecoration messageDecoration(ChatMessage message,) {
    return BoxDecoration(
      color: Colors.blueAccent,
      borderRadius: BorderRadius.circular(7),
    );
  }

  MessageOptions get messageOptions => MessageOptions(
        borderRadius: 6,
        onTapMedia: (ChatMedia media){
          // preview img if the media is image
          Navigator.push(context, MaterialPageRoute(
              builder: (context)=>PhotoViewPage(imgUrls: [media.url])
          ));
        },
        messageRowBuilder: (msg, preMsg, nextMsg, isAfterDateSeparator,
            isBeforeDateSeparator, {MessageOptions? messageOptions}) =>
            MessageRowWidget(
              message: msg,
              currentUser: controller.state.currUser,
              previousMessage: preMsg,
              nextMessage: nextMsg,
              isAfterDateSeparator: isAfterDateSeparator,
              isBeforeDateSeparator: isBeforeDateSeparator,
              messageOptions: messageOptions!,
            ),
        messageDecorationBuilder: (ChatMessage message,
            ChatMessage? previousMessage, ChatMessage? nextMessage) {
          return messageDecoration(message);
        },
        showOtherUsersAvatar: true,
        showCurrentUserAvatar: true,
        showOtherUsersName: false,
        marginSameAuthor: const EdgeInsets.only(top: 10),
        marginDifferentAuthor: const EdgeInsets.only(top: 10),
        onPressAvatar: (ChatUser chatUser) {
          print("press user ${chatUser.id}");
        },
        avatarBuilder: (ChatUser chatUser, Function? pressAvatar,  Function? longPressAvatar) {
          return ChatAvatar(
              user: chatUser,
              onLongPressAvatar: longPressAvatar,
              onPressAvatar: pressAvatar);
        });

  List<Widget> get trailing => bottomPanel.where((element) => element.condition).map((e) => InkWell(
    child: e.icon,
    onTap: ()=> e==_currBottomPanel?closeBottomPanel():openBottomPanel(e)
  )).toList();

}

/// 聊天视图 滚动控制器
final ScrollController scrollController = ScrollController();

/// 底部面板
class BottomPanel {

  /// 排序优先级
  final int sortedOrder;

  /// 面板内容
  final Widget panel;

  /// 面板高度
  final double height;

  /// 展示Icon
  final Icon icon;

  /// 条件展示
  bool condition;

  BottomPanel(this.sortedOrder, this.panel, this.height, this.icon, {this.condition=true});
}
